package ua.khpi.si.kit49.diploma.db.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ua.khpi.si.kit49.diploma.db.dto.City;

/**
 * 
 * implementation of cityDAO
 * 
 * @author netstalk3r
 * 
 */

@Repository("cityDAO")
public class CityDAOImpl implements CityDAO {
	
	///////////////////
	//Queries
	//////////////////
	private static final String QUERY_GET_ALL_CITIES = "FROM City";
	private static final String QUERY_GET_CITY_BY_ID = "FROM City WHERE id = :id";
	private static final String QUERY_GET_AMOUNT_OF_CITIES = "SELECT count(*) FROM City";

	@Autowired(required = true)
	private SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	@Override
	public List<City> getAllCities() {
		return sessionFactory.getCurrentSession()
				.createQuery(QUERY_GET_ALL_CITIES).list();
	}

	@Override
	public City getCityById(Integer id) {
		return (City) sessionFactory.getCurrentSession()
				.createQuery(QUERY_GET_CITY_BY_ID).setParameter("id", id)
				.uniqueResult();
	}

	@Override
	public Integer getAmountOfCity() {
		return ((Long) sessionFactory.getCurrentSession()
				.createQuery(QUERY_GET_AMOUNT_OF_CITIES).iterate().next())
				.intValue();
	}

}
